<script setup lang="ts">
import { ref } from 'vue'
// 引入组件
// 隐藏默认首页样式 pages.json
import { onLoad } from '@dcloudio/uni-app'
import CostomNavbar from './components/CustomNavbar.vue'
import CategoryPanel from './components/CategoryPanel.vue'
import HotPanel from './components/HotPanel.vue'
// 导入封装好的请求
import { getCategoryAPI, getHomebannerAPI, getHomeHotAPI } from '@/services/home'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import type { XtxGuessinstance } from '@/types/component'
// 获取首页轮播图数据
const bannerlist = ref<BannerItem[]>([])
const getHomebannerData = async () => {
  const res = await getHomebannerAPI()
  bannerlist.value = res.result
}
// 获取分类列表数据
const sortlist = ref<CategoryItem[]>([])
const getCategorylist = async () => {
  const res = await getCategoryAPI()
  sortlist.value = res.result
}
// 获取热门推荐数据
const hotlist = ref<HotItem[]>()
const getHomeHotlist = async () => {
  const res = await getHomeHotAPI()
  hotlist.value = res.result
}
// 在组件下拉触底时调用
const guessref = ref<XtxGuessinstance>()
const onScrollTolower = () => {
  guessref.value?.getmore()
}
// 页面的下拉刷新
const istriggered = ref(false)
const onRefresherrefresh = async () => {
  // 在触发后开启动画
  istriggered.value = true
  // 重置猜你喜欢分页数据
  guessref.value?.resetPage()
  // 使用promise.all() 方法使请求同步进行节省时间
  await Promise.all([
    getHomebannerData(),
    getCategorylist(),
    getHomeHotlist(),
    // 重新加载猜你喜欢数据
    guessref.value?.getmore(),
  ])
  // 页面刷新完成后关闭动画
  istriggered.value = false
}
// 在页面加载时调用
onLoad(() => {
  getHomebannerData()
  getCategorylist()
  getHomeHotlist()
})
</script>

<template>
  <!-- 自定义导航栏 -->
  <CostomNavbar />
  <scroll-view
    refresher-enabled
    :refresher-triggered="istriggered"
    @refresherrefresh="onRefresherrefresh"
    @scrolltolower="onScrollTolower"
    scroll-y
    class="scroll-view"
  >
    <!-- 轮播图 自动导入 组件间通信 父传子-->
    <XtxSwiper :list="bannerlist" />
    <!-- 分类标签 -->
    <CategoryPanel :list="sortlist" />
    <!-- 热门推荐 -->
    <HotPanel :list="(hotlist as HotItem[])" />
    <!-- 猜你喜欢 -->
    <XtxGuess ref="guessref" />
  </scroll-view>
</template>

<style lang="scss">
//
page {
  background-color: #f7f7f7;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.scroll-view {
  flex: 1; // 占满剩下的高度
}
</style>
